package com.ksy.common.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.ksy.common.R;
import com.ksy.common.dialog.BaseDialog;
import com.ksy.common.dialog.NoticeDialog;
import com.ksy.common.utils.DateUtil;
import com.ksy.common.utils.LogTool;
import com.ksy.common.utils.PermissionUtils;
import com.ksy.common.view.HeadBar;

/**
 * Created by Ksy.
 */

public class CommonBaseActivity extends AppCompatActivity {
    private Toast toast;
    private ImmersionBar mImmersionBar;
    private LinearLayout baseRootLayout;
    private HeadBar headBar;
    private ProgressDialog progressDialog;
    private long dialogStartShowTime;
    protected Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isShowRoot()) {
            super.setContentView(R.layout.common_activity_base);
            initBaseView();
        }
        if (isImmersionBarEnabled()) {
            mImmersionBar = ImmersionBar.with(this);
            initImmersionBar(mImmersionBar);
        }
    }

    protected boolean isImmersionBarEnabled() {
        return true;
    }

    protected boolean isShowRoot() {
        return true;
    }

    protected boolean isShowHeadBar() {
        return true;
    }

    @Override
    public void setContentView(int layoutResID) {
        this.setContentView(getLayoutInflater().inflate(layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        this.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        if (view != null && baseRootLayout != null) {
            baseRootLayout.removeView(view);
            baseRootLayout.addView(view, params);
        }
    }

    protected HeadBar getHeadBar() {
        return headBar;
    }


    private void initBaseView() {
        baseRootLayout = super.findViewById(R.id.baseActivityRootLayout);
        headBar = super.findViewById(R.id.baseActivityHeadBar);
        View vLine = super.findViewById(R.id.baseActivityVLine);
        headBar.setVisibility(isShowHeadBar() ? View.VISIBLE : View.GONE);
        vLine.setVisibility(isShowHeadBar() ? View.VISIBLE : View.GONE);
    }

    protected void initImmersionBar(ImmersionBar mImmersionBar) {
    }

    protected boolean isEmpty(String msg) {
        return TextUtils.isEmpty(msg);
    }

    protected boolean isNotEmpty(String msg) {
        return !TextUtils.isEmpty(msg);
    }

    protected boolean isSame(String msgL, String msgR) {
        return TextUtils.equals(msgL, msgR);
    }

    protected boolean isNotSame(String msgL, String msgR) {
        return !TextUtils.equals(msgL, msgR);
    }

    public void destroyActivity() {
        hideSoftInput();
        super.finish();
    }

    protected void destroyActivityWithAnimal() {
        hideSoftInput();
        super.finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    protected void onDestroy() {
        if (toast != null) {
            toast.cancel();
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
        super.onDestroy();
    }

    protected void showLog(Object o) {
        if (o == null) {
            LogTool.e("Log->  null");
            return;
        }
        LogTool.e("Log->  " + o.toString());
    }

    public void jump2Activity(Class cls) {
        if (cls != null) {
            Intent intent = new Intent(CommonBaseActivity.this, cls);
            startActivity(intent);
        }
    }

    public void jump2Activity(Class cls, int requestCode) {
        if (cls != null) {
            Intent intent = new Intent(CommonBaseActivity.this, cls);
            startActivityForResult(intent, requestCode);
        }
    }

    public void jump2Activity(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    public void jump2Activity(Intent intent) {
        if (intent != null) {
            startActivity(intent);
        }
    }

    protected void showToast(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        if (toast == null) {
            toast = Toast.makeText(CommonBaseActivity.this, msg, Toast.LENGTH_SHORT);
        }
        toast.setText(msg);
        toast.show();
    }

    @Override
    public void onBackPressed() {
        hideSoftInput();
        super.onBackPressed();
    }

    protected void showSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
    }

    protected void hideSoftInput() {
        try {
            View view = getCurrentFocus();
            if (view == null)
                view = new View(CommonBaseActivity.this);
            InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            if (imm == null)
                return;
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addFragment(int containerViewId, Fragment fragment) {
        if (fragment != null && !fragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().add(containerViewId, fragment).commitAllowingStateLoss();
        }
    }

    public void showFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded())
            getSupportFragmentManager().beginTransaction().show(fragment).commitAllowingStateLoss();
    }

    public void replaceFragment(int layoutId, Fragment fragment) {
        if (fragment != null)
            getSupportFragmentManager().beginTransaction().replace(layoutId, fragment).commitAllowingStateLoss();
    }

    public void hideFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded())
            getSupportFragmentManager().beginTransaction().hide(fragment).commitAllowingStateLoss();
    }

    protected void showDialog() {
        hideSoftInput();
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(CommonBaseActivity.this);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setCancelable(true);
            progressDialog.setMessage("请稍后...");
        }
        dialogStartShowTime = DateUtil.getCurrentTimeInMillis();
        progressDialog.show();
    }

    protected void hideDialog() {
        long rangeTime = DateUtil.getCurrentTimeInMillis() - dialogStartShowTime;
        if (rangeTime <= 800) {
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                }
            }, 800 - rangeTime);
        } else {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }
    }


    protected void toSetting(int requestCode) {
        PermissionUtils.toAppSetting(CommonBaseActivity.this, requestCode, getPackageName());
    }

    protected void showPermissionDialog(final int requestCode, String msg) {
        NoticeDialog noticeDialog = new NoticeDialog(CommonBaseActivity.this);
        noticeDialog.setMsg(msg);
        noticeDialog.setCancelable(false);
        noticeDialog.setOnClickListener(new NoticeDialog.ClickListener() {

            @Override
            public void enter(BaseDialog dialog) {
                dialog.dismiss();
                toSetting(requestCode);
            }
        });
        noticeDialog.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        onResult4Permission(requestCode);
    }

    protected void onResult4Permission(int requestCode) {

    }
}
